﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Core.Aria2c;
using System.Text.RegularExpressions;

namespace Download
{
    public partial class MainForm : Form
    {
        Basic b = new Download.Basic();
        public MainForm()
        {
            InitializeComponent();
            
        }

        private async void MainForm_Click(object sender, EventArgs e)
        {
            string version = await Aria2.GetVersion();
        }


        private async void button1_Click(object sender, EventArgs e)
        {
            Aria2cSettings set = new Aria2cSettings();
            set.Aria2Path = Application.StartupPath + "\\Package\\aria2c.exe";
            set.Aria2Args = Application.StartupPath + "\\Package\\aria2c.conf";
            set.Aria2Host = "127.0.0.1";
            set.Aria2Port = 36515;
            var isRun = await Aria2.RunAria2c(set);
            if (isRun)
            {
                statuLabAria2c.Text = "已启动";
            }
            else
            {
                statuLabAria2c.Text = "未启动";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Aria2.shutDownAria2c(36515);
            statuLabAria2c.Text = "未启动";
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            SetListView();
        }

        /// <summary>
        /// 自定义函数设置ListView控件初始属性
        /// </summary>
        private void SetListView()
        {
            //设置listView列标题头 宽度为9/13 2/13 2/13 
            //其中设置标题头自动适应宽度,-1根据内容设置宽度,-2根据标题设置宽度
            this.lvwNormal.Columns.Add("序号", 45, HorizontalAlignment.Center);
            this.lvwNormal.Columns.Add("下载类型", 80, HorizontalAlignment.Center);
            this.lvwNormal.Columns.Add("任务名称", 130, HorizontalAlignment.Center);
            this.lvwNormal.Columns.Add("文件大小", 130, HorizontalAlignment.Center);
            this.lvwNormal.Columns.Add("下载速度", 130, HorizontalAlignment.Center);
            this.lvwNormal.Columns.Add("开始时间", 130, HorizontalAlignment.Center);
            this.lvwNormal.Columns.Add("任务状态", 70, HorizontalAlignment.Center);
            //行和列是否显示网格线
            this.lvwNormal.GridLines = true;
            //显示方式(注意View是Details详细显示)
            this.lvwNormal.View = View.Details;
            //是否可编辑
            this.lvwNormal.LabelEdit = true;
            //没有足够的空间显示时,是否添加滚动条
            this.lvwNormal.Scrollable = true;
            //对表头进行设置
            this.lvwNormal.HeaderStyle = ColumnHeaderStyle.Clickable;
            //是否可以选择行
            this.lvwNormal.FullRowSelect = true;

            if (System.Windows.Forms.SystemInformation.TerminalServerSession)
                return;

            System.Reflection.PropertyInfo aProp =
                  typeof(System.Windows.Forms.Control).GetProperty(
                        "DoubleBuffered",
                        System.Reflection.BindingFlags.NonPublic |
                        System.Reflection.BindingFlags.Instance);

            aProp.SetValue(lvwNormal, true, null);

        }

        private async void btnAddM3U8Url_Click(object sender, EventArgs e)
        {
            string c = await Aria2.AddUri(txtM3U8Url.Text, "C:\\", "");


            string m3u8 = await b.getM3U8File(new CsharpHttpHelper.HttpItem { URL = txtM3U8Url.Text });

            if (m3u8 == "获取M3U8失败")
            {
                statusLabInfo.Text = m3u8;
                return;
            }
            List<string> downlst = Core.M3U8MediaInfo.M3U8MediaInfo.MediaParse(m3u8);

            foreach (ListViewItem item in lvwNormal.Items)
            {
                bool IsItRedundant = false;
                if (item.SubItems[1].Text == "M3U8")
                {
                    List<string> itemTag = item.Tag as List<string>;
                    for (int i = 0; i < downlst.Count; i++)
                    {
                        if (itemTag[i] != downlst[i]) { IsItRedundant = false; break; }
                        else IsItRedundant = true; 
                    }
                }
                if (IsItRedundant)
                {
                    statusLabInfo.Text = "任务已存在，请勿重复添加";
                    return;
                }
            }


            if (downlst.Count == 0)
            {
                statusLabInfo.Text = "获取M3U8下载地址出错";
                return;
            }

            ListViewItem listItem = new ListViewItem();

            listItem.Text = (lvwNormal.Items.Count + 1).ToString();    //显示文件名
            listItem.ForeColor = Color.Black;                            //设置行颜色
            listItem.Tag = downlst;

            listItem.SubItems.Add("M3U8");
            listItem.SubItems[1].Name = "下载类型";

            listItem.SubItems.Add(getUrlFileName(downlst[0]));
            listItem.SubItems[2].Name = "任务名称";

            listItem.SubItems.Add(downlst.Count.ToString());
            listItem.SubItems[3].Name = "文件大小";

            listItem.SubItems.Add("0");
            listItem.SubItems[4].Name = "下载速度";

            listItem.SubItems.Add(DateTime.Now.ToShortTimeString());
            listItem.SubItems[5].Name = "开始时间";

            listItem.SubItems.Add("未开始下载");
            listItem.SubItems[6].Name = "任务状态";

            lvwNormal.Invoke(new EventHandler(delegate
            {
                lvwNormal.Items.Add(listItem);
            }));
            
        }

        private string getUrlFileName(string url)
        {
            System.Text.RegularExpressions.Regex reg = new Regex(@".*?(?:[a-z][a-z\.\d\-]+)\.(?:[a-z][a-z\-]+)(?![\w\.]).*?((?:[a-z][a-z\.\d\-]+)\.(?:[a-z][a-z\-]+))(?![\w\.])", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);
            if (reg.IsMatch(url))
            {
                return reg.Match(url).Groups[1].Value;
            }
            else
            {
                return "";
            }
        }

        #region statusStip 提示信息自动清除

        int time = 0;

        private void tmrStatusLabInfo_Tick(object sender, EventArgs e)
        {
            time++;
            if (time > 20)
            {
                statusLabInfo.Text = "等待用户操作";
                tmrStatusLabInfo.Enabled = false;
            }
        }

        private void statusLabInfo_TextChanged(object sender, EventArgs e)
        {
            time = 0;
            if (!tmrStatusLabInfo.Enabled)
            {
                tmrStatusLabInfo.Enabled = true;
            }
        }

        #endregion

    }
}
